package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;


@Service("categoryService")
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2、组装成父子的树形结构
        //2、1）找到所有的一级分类
       /*   entities.stream().filter((categoryEntity)->{  //filter过滤 出 所有父节点为0的分类即为父分类后收集成一个集合tolist()
            return  categoryEntity.getParentCid() == 0;
        }).collect(Collectors.toList());
        return entities;*/
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity-> //filter过滤 出 所有父节点为0的分类即为父分类后收集成一个集合tolist
                categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    //递归查询获取所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
          List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
                return categoryEntity.getParentCid() == root.getCatId();
          }).map(categoryEntity ->{
              //1、找到子菜单 ， 递归找法
              categoryEntity.setChildren(getChildrens(categoryEntity,all));
              return categoryEntity;
          }).sorted((menu1,menu2)->{
              //2、菜单的排序
              return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
          }).collect(Collectors.toList());
          return children;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1、 删除之前先检查是否被其他地方引用

        //
        baseMapper.deleteBatchIds(asList);

    }


    /**
     * 找到catelogId的完整路径
     * [父/子/孙]
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> findParentPath = findParentPath(catelogId,paths);
        Collections.reverse(findParentPath);
        return (Long[]) findParentPath.toArray(new Long[findParentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @CacheEvict(value = "category",key = "'getLevel1Categorys'") //失效模式  删除缓存  注意：key属性一定要加单引号保证SpEL语法正确
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }


    @Cacheable(value = {"category"},key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys方法被调用了");
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }



    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {

       //TODO 将数据库的多次查询变一次 时间换空间
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> categoryEntities = getLevel1Categorys();
        //2、封装数据
        Map<String, List<Catelog2Vo>> parent_cid = categoryEntities.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            //2、封装上面的结果；
            List<Catelog2Vo> catelog2Vos = null;
            if (entities != null) {
                catelog2Vos = entities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1、找当前2级分类的3级分类封装成vo
                    List<CategoryEntity> level3Catelog = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    if(level3Catelog!=null){
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(),l3.getCatId().toString(),l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parent_cid;
    }


    public Map<String, List<Catelog2Vo>> getCatelogJson2(){
        //给缓存中放JSON字符串，拿出的json字符串还要逆转为能用的对象类型，这个过程其实就是序列化与反序列化过程；

        //1、加入redis缓存逻辑，缓存中存的所有对象都是json字符串。
        //JSON跨语言，跨平台兼容。
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");

        if(StringUtils.isEmpty(catalogJSON)){
            //2、缓存中没有，查询数据库
            Map<String, List<Catelog2Vo>> catelogJsonFromDb = getCatelogJsonFromDbWithRedisLock();
            return catelogJsonFromDb;
        }

        //将查询的json字符串转为对象     这里的TypeReference是受保护的，我们需要实现接口，这里通过匿名内部类来实现
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON,new TypeReference<Map<String, List<Catelog2Vo>>>(){});
        return result;
    }


    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedissonLock() {

        //1、锁的名字决定了锁的粒度； 粒度决定效率类似本地锁静态锁效率没有模块儿锁高；
        RLock lock = redisson.getLock("CatelogJson-lock");
        lock.lock();
            Map<String, List<Catelog2Vo>> dataDromDb;
            try {
                dataDromDb = getDataDromDb();
            }finally {
                lock.unlock();
            }
            return dataDromDb;

    }


    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedisLock() {
            //1、占分布式锁，去redis占坑（大家都去给redis保存一个相同的键都来执行该方法）
        //使用原子命令占锁并且设置过期时间，防止比如宕机来不及删锁时候出现死锁情况
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
        if(lock){
            //加锁成功
            System.out.println("获取分布式锁成功");
          /*  //2、设置锁的过期时间，防止比如宕机来不及删锁时候出现死锁情况
            redisTemplate.expire("lock",30,TimeUnit.MINUTES);*/
            Map<String, List<Catelog2Vo>> dataDromDb;
            //获取值对比+对比成功删除=原子操作    Lua脚本解锁
            try {
                dataDromDb = getDataDromDb();
            }finally {
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
              //删除锁
              Long lock1 = redisTemplate.execute(new DefaultRedisScript<>(script,Long.class),Arrays.asList("lock"),uuid);
            }
         /*  //必须使用原子操作删除
            String lockValue = redisTemplate.opsForValue().get("lock");
            if(uuid.equals(lockValue)){
                //删除自己的锁
                redisTemplate.delete("lock");
            }*/
            return dataDromDb;
        }else {
            //加锁失败....重试。 synchronized()类似自旋，一直重试
            //休眠100ms重试
            System.out.println("获取分布式锁失败。。等待重试");
            try {
                Thread.sleep(200);
            } catch (Exception e) {

            }
            return getCatelogJsonFromDbWithLocalLock(); //自旋方式
        }
    }

    private Map<String, List<Catelog2Vo>> getDataDromDb(){
        //得到锁会后，我们应该在去缓存中确定一次，如果没有才需要继续查询
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        //如果缓存不为null直接返回
        if(!StringUtils.isEmpty(catalogJSON)){
            //将查询的json字符串转为对象     这里的TypeReference是受保护的，我们需要实现接口，这里通过匿名内部类来实现
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON,new TypeReference<Map<String, List<Catelog2Vo>>>(){});
            return result;
        }
        //TODO 将数据库的多次查询变一次 时间换空间
        /*        List<CategoryEntity> selectList = baseMapper.selectList(null);*/
        List<CategoryEntity> categoryEntities = getLevel1Categorys();
        //2、封装数据
        Map<String, List<Catelog2Vo>> parent_cid = categoryEntities.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            //2、封装上面的结果；
            List<Catelog2Vo> catelog2Vos = null;
            if (entities != null) {
                catelog2Vos = entities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1、找当前2级分类的3级分类封装成vo
                    List<CategoryEntity> level3Catelog = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    if(level3Catelog!=null){
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(),l3.getCatId().toString(),l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));

        //3、查到的数据在放入缓存,将对象转为json放入缓存中
        String s = JSON.toJSONString(parent_cid);//任意对象转为JSON字符串
        redisTemplate.opsForValue().set("catalogJSON",s,1,TimeUnit.DAYS);
        return parent_cid;

    }











    //从数据库查询并封装分类数据
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithLocalLock() {
        /**
         * 将数据库的多次查询变一次
         */
        //只要是同一把锁，就能锁住需要这个锁的所有线程
        //synchronized（this）表示当前的，springboot所有的组件在容器中都是单例的，
       synchronized (this){
           //得到锁会后，我们应该在去缓存中确定一次，如果没有才需要继续查询
           String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
           //如果缓存不为null直接返回
           if(!StringUtils.isEmpty(catalogJSON)){
               //将查询的json字符串转为对象     这里的TypeReference是受保护的，我们需要实现接口，这里通过匿名内部类来实现
               Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON,new TypeReference<Map<String, List<Catelog2Vo>>>(){});
               return result;
           }
           //TODO 将数据库的多次查询变一次 时间换空间
           /*        List<CategoryEntity> selectList = baseMapper.selectList(null);*/
           //1、查出所有1级分类；
           List<CategoryEntity> categoryEntities = getLevel1Categorys();

           //2、封装数据
           Map<String, List<Catelog2Vo>> parent_cid = categoryEntities.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
               //1、拿到每一个的1级分类，查到这个一级分类的二级分类
               List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
               //2、封装上面的结果；
               List<Catelog2Vo> catelog2Vos = null;
               if (entities != null) {
                   catelog2Vos = entities.stream().map(l2 -> {
                       Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                       //1、找当前2级分类的3级分类封装成vo
                       List<CategoryEntity> level3Catelog = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                       if(level3Catelog!=null){
                           List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                               //2、封装成指定格式
                               Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(),l3.getCatId().toString(),l3.getName());
                               return catelog3Vo;
                           }).collect(Collectors.toList());
                           catelog2Vo.setCatalog3List(collect);
                       }
                       return catelog2Vo;
                   }).collect(Collectors.toList());
               }
               return catelog2Vos;
           }));

           //3、查到的数据在放入缓存,将对象转为json放入缓存中
           String s = JSON.toJSONString(parent_cid);//任意对象转为JSON字符串
           redisTemplate.opsForValue().set("catalogJSON",s,1,TimeUnit.DAYS);
           return parent_cid;
       }


    }


    //225
    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1、收集当前节点ID
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }

        return paths;
    }
}